package com.atiguigu.spring6.validator.one;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        // name不能为空
        ValidationUtils.rejectIfEmpty(errors,"name","name.empty","name不能为空");

        // age不能为空
        Person person = (Person) target;
        if (person.getAge() == null) {
            errors.rejectValue("age","age.empty","age不能为空");
        } else if (person.getAge() < 0 || person.getAge() > 200) {
            errors.rejectValue("age","age.illegal","age不合法");
        }
    }
}
